<template>
  <div class="main-location">
    <el-popover placement="bottom" width="328" trigger="click" v-if="show">
      <div slot="reference" class="show">
        <div style="float:left" class="a">
          <div style="height:24px;width:1px;background:#ff6767"></div>
          <div style="height:24px;width:1px;background:#d12a2a"></div>
        </div>
        <div class="name">{{name}}</div>
        <div style="float:right" class="a">
          <div style="height:24px;width:1px;background:#ff6767"></div>
          <div style="height:24px;width:1px;background:#d12a2a"></div>
        </div>
      </div>
      <div id="pop">
        <div class="city">城市列表</div>
        <div class="present-city">当前城市: {{name}}</div>
        <!-- 联级选择器 -->
        <el-cascader
          :options="option"
          v-model="selectedOptions"
          @change="handleChange"
          @active-item-change="handleItemChange"
          style="width:100%"
          size="medium"
          placeholder="请在此选择城市"
          label
        ></el-cascader>
        <!-- <el-input placeholder="请输入城市" v-model="selectedOptions" >
					<el-button slot="append" icon="el-icon-search" @click="search"></el-button>
        </el-input>-->
        <div class="citys">
          <vue-scroll :ops="ops">
            <div class="box" v-for="(item) in options" :key="item.key">
              <div style="float:left;width:50px;">{{item.label}}:</div>
              <ul style="float:left; width: calc(100% - 50px);">
                <li
                  v-for="(items) in item.children"
                  :key="items.key"
                  @click="city_click(item, items)"
                >{{items.label}}</li>
              </ul>
            </div>
          </vue-scroll>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script>
import Config from '../config'
import moment from 'moment'
// import { provinceAndCityData } from 'element-china-area-data'
import { provinceAndCityData } from 'static/js/regionData'
import { mapMutations } from 'vuex'
import jsonp from 'jsonp'
export default {
  name: 'MainLocation',
  data() {
    return {
      ops: {
        bar: {
          background: '#DDDEE0',
          onlyShowBarOnScroll: false,
        }
      },
      name: '',
      option: [],
      options: provinceAndCityData,
      selectedOptions: null,
      show: true
    }
  },
  watch: {
    $route() {
      // 页面判断
      if (this.$route.path === "/show/location") {
        this.show = true
        this.stye_click()
      } else {
        this.show = false
      }
    }
  },
  methods: {
    ...mapMutations('user', [
      'setUser',
      'setRole',
      'setDistrict',
      'setModule'
    ]),
    // 二级选择器
    search() {
      // console.log(this.selectedOptions)
    },
    // 获取选择器省级
    group_by_province() {
      let province = []
      let url = `${Config.DEVICE_MANAGE_URL}/storehouses/group_by_province`;
      this.$http.get(url).then(res => {
        if (res) {
          if (res.array.length) {
            res.array.map((item) => {
              provinceAndCityData.map((items) => {
                if (item.province === items.value) {
                  province.push({ value: items.value, label: items.label, children: []})
                }
              })
            })
          }
        }
        this.option = province
      });
    },
    // 选择器城市
    handleItemChange(value) {
      let city = []
      let url = `${Config.DEVICE_MANAGE_URL}/storehouses/group_by_city?province=${value[0]}`;
      this.$http.get(url).then(res => {
        if (res) {
          provinceAndCityData.map((item) => {
            if (item.value === value[0]) {
              item.children.map((c) => {
                res.array.map((cs) => {
                  if (c.value === cs.city) {
                    city.push(c)
                  }
                })
              })
            }
          })
        }
        this.option.map((item) => {
          if (item.value === value[0]) {
            item.children = city
          }
        })
      });
    },
    // 选择器改变
    handleChange(value) {
      provinceAndCityData.map((item, i) => {
        if (item.value === value[0]) {
          item.children.map((items, i) => {
            if (items.value === value[1]) {
              if (items.label === '市辖区' || items.label === '县') {
                this.name = item.label
              } else {
                // 针对济源市单独处理
                if (item.label === '河南省' && items.label === '直辖县') {
                  this.name = '济源市'
                } else {
                  this.name = items.label
                }
              }
              // 存入城市
              let obj = JSON.parse(JSON.stringify(this.$store.state.user.district))
              obj.city = [item.value, items.value]
              obj.city_name = this.name
              this.setDistrict(obj)
            }
          })
        }
      })
    },
    // 地理选择
    city_click(data, child_data) {
      if (child_data.label === '市辖区' || child_data.label === '县') {
        this.name = data.label
      } else {
        this.name = child_data.label
      }

      // 存入城市
      let obj = JSON.parse(JSON.stringify(this.$store.state.user.district))
      obj.city = [data.value, child_data.value]
      obj.city_name = this.name
      this.setDistrict(obj)
      // 更改输入框
      this.selectedOptions = []
    },
    // 获取城市
    get_city() {
      return new Promise((resolve, reject) => {
        var that = this
        let obj = JSON.parse(JSON.stringify(this.$store.state.user.district))
        // 不同角色加入不同省,市
        if (obj.provinceCode) {
          obj.city = [obj.provinceCode]
          if (obj.cityCode) {
            obj.city.push(obj.cityCode)
          }
          that.setDistrict(obj)
          resolve()
        } else {
          //获取浏览器定位
          var geolocation = new BMap.Geolocation();
          geolocation.getCurrentPosition((res) => {
            let url = `//api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=${res.point.lat},${res.point.lng}&output=json&pois=1&ak=A8uCXyn80KLhb7nCGNjpqLdRwhFW7EeU`
            jsonp(url, {
              timeout: 5000
            }, (err, json) => {
              if (!err) {
                // obj.city = [json.result.addressComponent.adcode.substring(0, 2) + '0000', json.result.addressComponent.adcode.substring(0, 4) + '00']
                obj.city = [that.$substring.province(json.result.addressComponent.adcode), that.$substring.city(json.result.addressComponent.adcode)]
                that.setDistrict(obj)
                resolve()
              } else {
                this.$message.error('网络延迟过高,请稍后重试!');
              }
            })
          })
          // obj.city = [(obj.districtId + '').substring(0, 2) + '0000', obj.districtId + '']
        }
      })
    },
    get_name() {

      this.get_city().then(() => {
        let obj = JSON.parse(JSON.stringify(this.$store.state.user.district))
        if (obj.city.length > 1) {
          provinceAndCityData.map((item) => {
            if (item.value === obj.city[0]) {

              item.children.map((items) => {
                console.log(obj.city[1])

                if (items.value === obj.city[1]) {
                  if (items.label === '市辖区' ||  items.label === '县') {
                    this.name = item.label
                  } else {
                    this.name = items.label
                  }
                }
              })
            }
          })
        } else {

          provinceAndCityData.map((item) => {
            if (item.value === obj.city[0]) {
              this.name = item.label
            }
          })
				}
        obj.city_name = this.name
        this.setDistrict(obj)
      })
    },
    stye_click() {
      // 角色权限按钮
      if (!this.$store.state.user.district.provinceCode && !this.$store.state.user.district.cityCode && !this.$store.state.user.district.areaCode || this.$store.state.user.district.provinceCode && !this.$store.state.user.district.cityCode && !this.$store.state.user.district.areaCode || this.$store.state.user.district.provinceCode && this.$store.state.user.district.cityCode && !this.$store.state.user.district.areaCode) {
        // 没有city
        if (!this.$store.state.user.district.city) {
          // 不同角色显示不同城市
          if (this.$store.state.user.district.provinceCode) {
            provinceAndCityData.map((item) => {
              if (item.value === this.$store.state.user.district.provinceCode) {
                this.options = [item]
              }
            })
          } else {
            this.options = provinceAndCityData
          }
          this.get_name()

        } else {
          this.name = this.$store.state.user.district.city_name
          // this.selectedOptions = this.$store.state.user.district.city
        }
      } else {
        this.show = false // 角色权限控制按钮
      }

    }
  },
  mounted() {
    // 页面判断
    if (this.$route.path === "/show/location") {
      this.show = true
      this.stye_click()
    } else {
      this.show = false
    }

    this.group_by_province()
  },
  created() {
  }
}
</script>

<style lang="scss">
.main-location {
  .show {
    width: 120px;
    cursor: pointer;
    line-height: 60px;
    height: 60px;
    text-align: center;
    .name {
      width: 50px;
      height: 60px;
      display: inline-block;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .a {
      margin-top: 18px;
      div {
        float: left;
      }
    }
    &:after {
      content: "";
      vertical-align: 24px;
      border: 4px solid transparent;
      border-top-color: #fff;
      display: inline-block;
    }
    &:hover {
      background-color: #da2929;
      .a {
        display: none;
      }
    }
  }
}
#pop {
  width: 100%;
  height: 328px;
  box-sizing: border-box;
  padding: 4px;
  .city {
    height: 27px;
    border-bottom: 1px solid #efeaea;
    font-size: 14px;
    color: $gray3;
  }
  .present-city {
    height: 43px;
    font-size: 14px;
    color: $gray3;
    line-height: 43px;
  }
  .el-input__inner {
    height: 32px;
  }
  .el-input.is-focus .el-input__inner {
    border-color: #da2929;
  }
  .citys {
    margin-top: 20px;
    width: 100%;
    height: 182px;
    .box {
      color: #2e48e5;
      overflow: hidden;
      margin-bottom: 12px;
      li {
        cursor: pointer;
        float: left;
        margin: 0 6px 12px 6px;
      }
    }
  }
}
</style>
